<template>
  <div class="starrocks-query-logs">
    <div class="page-header">
      <div class="title-with-back">
        <el-button
          type="primary"
          :icon="ArrowLeft"
          @click="goBack"
          class="blue-return-button"
          circle
        />
        <div class="title-content">
          <div class="title-main">
            <el-icon class="title-icon"><DataAnalysis /></el-icon>
            <h2>StarRocks 查询日志分析</h2>
          </div>
          <p class="page-description">
            <el-icon><TrendCharts /></el-icon>
            <span>SQL 审计和慢查询分析，支持用户、数据库、执行时间等多维度筛选</span>
          </p>
        </div>
      </div>
      <div class="page-actions">
        <el-select v-model="selectedCluster" placeholder="全部集群" clearable style="width: 200px" @change="refreshData">
          <el-option label="全部集群" value="" />
          <el-option
            v-for="cluster in clusterOptions"
            :key="cluster"
            :label="cluster.toUpperCase()"
            :value="cluster"
          />
        </el-select>
        <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="loading">刷新</el-button>
      </div>
    </div>

    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <span><el-icon><Timer /></el-icon> 时间范围</span>
        </div>
      </template>
      <div class="time-selector">
        <div class="time-quick-buttons">
          <el-button
            v-for="option in timeOptions"
            :key="option.value"
            :class="['time-btn', option.buttonClass, { active: selectedTimeRange === option.value }]"
            @click="selectTimeRange(option.value)"
            size="default"
          >
            {{ option.label }}
          </el-button>
        </div>
        <div class="custom-time-selector">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleCustomTimeChange"
            style="width: 280px;"
          />
          <el-time-picker
            v-model="startTime"
            placeholder="开始时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            @change="handleCustomTimeChange"
            style="width: 120px;"
          />
          <span class="time-separator">至</span>
          <el-time-picker
            v-model="endTime"
            placeholder="结束时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            @change="handleCustomTimeChange"
            style="width: 120px;"
          />
        </div>
      </div>
    </el-card>

    <el-row :gutter="20" class="overview-row" v-loading="loading">
      <el-col :span="6" v-for="card in overviewCards" :key="card.label">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :class="card.type">
              <el-icon><component :is="card.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ card.value }}</div>
              <div class="stat-label">{{ card.label }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="distribution-card" v-loading="loading">
          <template #header>
            <div class="card-header">
              <span><el-icon><DataBoard /></el-icon> 集群分布</span>
            </div>
          </template>
          <el-table :data="clusterDistribution" height="320" empty-text="暂无数据">
            <el-table-column prop="cluster" label="集群" min-width="120">
              <template #default="scope">{{ scope.row.cluster?.toUpperCase?.() || 'UNKNOWN' }}</template>
            </el-table-column>
            <el-table-column prop="query_count" label="查询数" width="120" align="right" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="distribution-card" v-loading="loading">
          <template #header>
            <div class="card-header">
              <span><el-icon><Grid /></el-icon> 数据库分布</span>
            </div>
          </template>
          <el-table :data="databaseDistribution" height="320" empty-text="暂无数据">
            <el-table-column prop="database" label="数据库" min-width="120" show-overflow-tooltip />
            <el-table-column prop="query_count" label="查询数" width="100" align="right" />
            <el-table-column prop="slow_query_count" label="慢查询" width="100" align="right" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="trend-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span><el-icon><TrendCharts /></el-icon> 查询趋势（{{ trendGranularityLabel }}）</span>
        </div>
      </template>
      <div ref="trendChartRef" class="trend-chart"></div>
    </el-card>

    <el-card class="user-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span><el-icon><User /></el-icon> 用户行为分析 Top {{ userTopN }}</span>
        </div>
      </template>
      <el-table :data="userStats" height="360" empty-text="暂无用户数据">
        <el-table-column prop="user" label="用户" width="150" show-overflow-tooltip />
        <el-table-column prop="total_queries" label="查询总数" width="100" align="right" />
        <el-table-column prop="slow_query_count" label="慢查询数" width="100" align="right" />
        <el-table-column prop="success_rate" label="成功率" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getSuccessRateTag(scope.row.success_rate)" size="small">
              {{ scope.row.success_rate }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="avg_exec_time" label="平均执行时间(ms)" width="150" align="right" />
        <el-table-column prop="last_query_time" label="最近查询时间" min-width="180" />
      </el-table>
    </el-card>

    <el-card class="sql-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span><el-icon><Document /></el-icon> SQL执行耗时分析 Top {{ sqlTopN }}</span>
        </div>
      </template>
      <el-table :data="topQueries" height="400" empty-text="暂无SQL数据">
        <el-table-column prop="sample_query" label="SQL示例" min-width="350" show-overflow-tooltip>
          <template #default="scope">
            <div class="sql-cell">
              <span class="sql-text">{{ scope.row.sample_query }}</span>
              <el-button 
                :icon="DocumentCopy" 
                size="small" 
                text 
                @click="copySQL(scope.row.sample_query)"
                class="copy-btn"
                title="复制SQL"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="avg_exec_time" label="执行时间(ms)" width="120" align="right" sortable>
          <template #default="scope">
            <el-tag :type="scope.row.avg_exec_time > 10000 ? 'danger' : scope.row.avg_exec_time > 1000 ? 'warning' : 'success'" size="small">
              {{ scope.row.avg_exec_time }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="query_user" label="用户" width="120" show-overflow-tooltip />
        <el-table-column prop="query_database" label="数据库" width="120" show-overflow-tooltip />
        <el-table-column prop="scan_rows" label="扫描行数" width="120" align="right" />
        <el-table-column prop="return_rows" label="返回行数" width="120" align="right" />
        <el-table-column prop="last_exec_time" label="执行时间" min-width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Refresh,
  Timer,
  DataAnalysis,
  TrendCharts,
  Grid,
  DataBoard,
  Document,
  User,
  DocumentCopy
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import api from '@/utils/api'

const router = useRouter()

const loading = ref(false)
const clusterOptions = ref([])
const selectedCluster = ref('')

const selectedTimeRange = ref('all')
const dateRange = ref([])
const startTime = ref('00:00:00')
const endTime = ref('23:59:59')

const overview = reactive({
  totals: {
    total_queries: 0,
    slow_query_count: 0,
    success_count: 0,
    error_count: 0,
    user_count: 0,
    database_count: 0,
    cluster_count: 0,
    last_query_time: ''
  },
  cluster_distribution: [],
  database_distribution: []
})

const trendChartRef = ref(null)
let trendChart = null
const trendGranularityLabel = ref('按小时')
const trendData = ref([])

const userStats = ref([])
const userTopN = ref(20)

const topQueries = ref([])
const sqlTopN = ref(20)

const timeOptions = [
  { value: 'all', label: '全部', buttonClass: 'time-btn-all' },
  { value: '1h', label: '1小时', buttonClass: 'time-btn-1h' },
  { value: '6h', label: '6小时', buttonClass: 'time-btn-6h' },
  { value: '1d', label: '1天', buttonClass: 'time-btn-1d' },
  { value: '3d', label: '3天', buttonClass: 'time-btn-3d' },
  { value: '7d', label: '7天', buttonClass: 'time-btn-7d' }
]

const overviewCards = computed(() => [
  { label: '查询总数', value: overview.totals.total_queries?.toLocaleString() || 0, icon: DataAnalysis, type: 'total' },
  { label: '慢查询', value: overview.totals.slow_query_count?.toLocaleString() || 0, icon: TrendCharts, type: 'slow' },
  { label: '成功查询', value: overview.totals.success_count?.toLocaleString() || 0, icon: DataBoard, type: 'success' },
  { label: '错误查询', value: overview.totals.error_count?.toLocaleString() || 0, icon: Document, type: 'error' }
])

const clusterDistribution = computed(() => overview.cluster_distribution || [])
const databaseDistribution = computed(() => overview.database_distribution || [])

const goBack = () => {
  router.back()
}

const fetchClusters = async () => {
  try {
    const response = await api.get('/logs/starrocks-query/clusters')
    if (response.data.success) {
      clusterOptions.value = response.data.data.clusters || []
    }
  } catch (error) {
    ElMessage.warning('获取集群列表失败：' + (error.message || '未知错误'))
  }
}

const getTimeRangeParams = () => {
  const now = new Date()
  const end = formatLocalDateTime(now)

  if (selectedTimeRange.value === 'all') {
    // 全部时默认查询最近30天的数据
    const start = formatLocalDateTime(new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000))
    return { start_time: start, end_time: end }
  }

  if (selectedTimeRange.value === 'custom' && dateRange.value.length === 2) {
    return {
      start_time: `${dateRange.value[0]} ${startTime.value || '00:00:00'}`,
      end_time: `${dateRange.value[1]} ${endTime.value || '23:59:59'}`
    }
  }

  let start = ''

  switch (selectedTimeRange.value) {
    case '1h':
      start = formatLocalDateTime(new Date(now.getTime() - 60 * 60 * 1000))
      break
    case '6h':
      start = formatLocalDateTime(new Date(now.getTime() - 6 * 60 * 60 * 1000))
      break
    case '1d':
      start = formatLocalDateTime(new Date(now.getTime() - 24 * 60 * 60 * 1000))
      break
    case '3d':
      start = formatLocalDateTime(new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000))
      break
    case '7d':
      start = formatLocalDateTime(new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000))
      break
    default:
      start = ''
  }

  return start ? { start_time: start, end_time: end } : {}
}

const formatLocalDateTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const getGranularity = () => {
  if (selectedTimeRange.value === 'all') {
    // 全部时默认按天展示（最近30天）
    trendGranularityLabel.value = '按天'
    return 'day'
  }

  if (selectedTimeRange.value === 'custom' && dateRange.value.length === 2) {
    const start = new Date(dateRange.value[0])
    const end = new Date(dateRange.value[1])
    const diffDays = (end - start) / (1000 * 60 * 60 * 24)
    if (diffDays <= 1) {
      trendGranularityLabel.value = '按小时'
      return 'hour'
    }
    if (diffDays <= 7) {
      trendGranularityLabel.value = '按小时'
      return 'hour'
    }
    trendGranularityLabel.value = '按天'
    return 'day'
  }

  switch (selectedTimeRange.value) {
    case '1h':
      trendGranularityLabel.value = '按分钟'
      return 'minute'
    case '6h':
    case '1d':
    case '3d':
      trendGranularityLabel.value = '按小时'
      return 'hour'
    case '7d':
      trendGranularityLabel.value = '按天'
      return 'day'
    default:
      trendGranularityLabel.value = '按小时'
      return 'hour'
  }
}

const fetchOverview = async () => {
  const params = {
    ...getTimeRangeParams()
  }
  if (selectedCluster.value) {
    params.cluster = selectedCluster.value
  }

  const response = await api.get('/logs/starrocks-query/overview', { params })
  if (response.data.success) {
    const data = response.data.data
    overview.totals = data.totals || overview.totals
    overview.cluster_distribution = data.cluster_distribution || []
    overview.database_distribution = data.database_distribution || []
  }
}

const fetchTrend = async () => {
  const params = {
    ...getTimeRangeParams(),
    granularity: getGranularity()
  }
  if (selectedCluster.value) {
    params.cluster = selectedCluster.value
  }

  const response = await api.get('/logs/starrocks-query/trend', { params })
  if (response.data.success) {
    trendData.value = response.data.data.trends || []
    renderTrendChart()
  }
}

const fetchUserStats = async () => {
  const params = {
    ...getTimeRangeParams(),
    top_n: userTopN.value
  }
  if (selectedCluster.value) {
    params.cluster = selectedCluster.value
  }

  const response = await api.get('/logs/starrocks-query/user-stats', { params })
  if (response.data.success) {
    userStats.value = response.data.data.user_stats || []
  }
}

const fetchTopQueries = async () => {
  const params = {
    ...getTimeRangeParams(),
    top_n: sqlTopN.value,
    order_by: 'time'  // 按执行时间排序
  }
  if (selectedCluster.value) {
    params.cluster = selectedCluster.value
  }

  const response = await api.get('/logs/starrocks-query/top-queries', { params })
  if (response.data.success) {
    topQueries.value = response.data.data.top_queries || []
  }
}

const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([fetchOverview(), fetchTrend(), fetchUserStats(), fetchTopQueries()])
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('刷新数据失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

const selectTimeRange = (range) => {
  selectedTimeRange.value = range
  dateRange.value = []
  startTime.value = '00:00:00'
  endTime.value = '23:59:59'
  refreshData()
}

const handleCustomTimeChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    selectedTimeRange.value = 'custom'
    refreshData()
  }
}

const renderTrendChart = () => {
  if (!trendChartRef.value) return

  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }

  const categories = ['TOTAL', 'SLOW', 'ERROR']
  const categoryConfig = {
    TOTAL: { color: '#409eff', name: '总查询数' },
    SLOW: { color: '#e6a23c', name: '慢查询' },
    ERROR: { color: '#f56c6c', name: '错误查询' }
  }

  const times = trendData.value.map(item => item.time)
  const series = categories.map(category => ({
    name: categoryConfig[category]?.name || category,
    type: 'line',
    smooth: true,
    showSymbol: false,
    itemStyle: { color: categoryConfig[category]?.color || '#909399' },
    data: trendData.value.map(item => item[category]?.query_count || 0)
  }))

  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: categories.map(c => categoryConfig[c]?.name || c), bottom: 0 },
    grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: times
    },
    yAxis: {
      type: 'value',
      name: '查询数'
    },
    series
  }

  trendChart.setOption(option)
}

const getSuccessRateTag = (rate) => {
  if (rate >= 95) return 'success'
  if (rate >= 80) return 'warning'
  return 'danger'
}

const getSlowRateTag = (rate) => {
  if (rate < 10) return 'success'
  if (rate < 30) return 'warning'
  return 'danger'
}

const copySQL = async (sql) => {
  try {
    await navigator.clipboard.writeText(sql)
    ElMessage.success('SQL已复制到剪贴板')
  } catch (error) {
    // 降级方案：使用传统方法
    const textarea = document.createElement('textarea')
    textarea.value = sql
    textarea.style.position = 'fixed'
    textarea.style.opacity = '0'
    document.body.appendChild(textarea)
    textarea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('SQL已复制到剪贴板')
    } catch (err) {
      ElMessage.error('复制失败，请手动复制')
    }
    document.body.removeChild(textarea)
  }
}

onMounted(async () => {
  await fetchClusters()
  await refreshData()

  window.addEventListener('resize', () => {
    if (trendChart) {
      trendChart.resize()
    }
  })
})

onBeforeUnmount(() => {
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
})
</script>

<style scoped>
.starrocks-query-logs {
  padding: 0;
}

.page-header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.title-with-back {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.title-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.title-main {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-main h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.page-description {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #606266;
  margin: 0;
}

.page-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.blue-return-button {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.blue-return-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.4);
  background: linear-gradient(135deg, #66b3ff 0%, #409eff 100%);
}

.filter-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.time-selector {
  display: flex;
  align-items: center;
  gap: 16px;
}

.time-quick-buttons {
  display: flex;
  gap: 8px;
}

.time-btn {
  border: 2px solid;
  font-weight: 500;
  transition: all 0.3s ease;
}

.time-btn-all { border-color: #909399; color: #606266; background-color: #f4f4f5; }
.time-btn-all:hover { border-color: #909399; color: #606266; background-color: #e9e9eb; }
.time-btn-all.active { border-color: #909399; color: #fff; background-color: #909399; }

.time-btn-1h { border-color: #9b59b6; color: #9b59b6; background-color: #f3e8ff; }
.time-btn-1h.active { background: #9b59b6; color: #fff; }

.time-btn-6h { border-color: #8e44ad; color: #8e44ad; background-color: #f4ecff; }
.time-btn-6h.active { background: #8e44ad; color: #fff; }

.time-btn-1d { border-color: #409eff; color: #409eff; background-color: #ecf5ff; }
.time-btn-1d.active { background: #409eff; color: #fff; }

.time-btn-3d { border-color: #e6a23c; color: #e6a23c; background-color: #fdf6ec; }
.time-btn-3d.active { background: #e6a23c; color: #fff; }

.time-btn-7d { border-color: #67c23a; color: #67c23a; background-color: #f0f9ff; }
.time-btn-7d.active { background: #67c23a; color: #fff; }

.custom-time-selector {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time-separator {
  color: #909399;
}

.overview-row {
  margin-bottom: 16px;
}

.stat-card {
  height: 130px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: white;
}

.stat-icon.total { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-icon.slow { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-icon.success { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-icon.error { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }

.stat-info { flex: 1; min-width: 0; }
.stat-value { font-size: 28px; font-weight: bold; color: #303133; }
.stat-label { font-size: 13px; color: #909399; margin-top: 6px; }

.distribution-card,
.trend-card,
.user-card,
.sql-card {
  margin-bottom: 16px;
}

.trend-chart {
  width: 100%;
  height: 360px;
}

/* SQL表格样式 - 防止换行 */
.sql-card :deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

.sql-card :deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* SQL单元格样式 */
.sql-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.sql-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.copy-btn {
  flex-shrink: 0;
  opacity: 0;
  transition: opacity 0.3s;
  padding: 4px;
  margin-left: auto;
}

.sql-cell:hover .copy-btn {
  opacity: 1;
}

.copy-btn:hover {
  color: #409eff;
}
</style>
